<template>
  <view class="chart-container">
    <!-- 使用 l-echart 组件（需要先安装） -->
    <l-echart ref="chartRef" @finished="initChart" :canvas-id="canvasId" class="chart"></l-echart>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'SimpleIntradayChart',
  props: {
    canvasId: {
      type: String,
      default: 'intraday-chart'
    }
  },
  
  setup() {
    const chartRef = ref(null);
    let myChart = null;

    // 简化的时间处理函数
    const roundTime = (date, unit, useUTC) => {
      const d = new Date(date);
      if (unit === 'day' && useUTC) {
        d.setUTCHours(0, 0, 0, 0);
      }
      return d;
    };

    const formatTime = (timestamp, format, useUTC) => {
      const date = new Date(timestamp);
      const methods = useUTC ? 'UTC' : '';
      
      return format.replace(/{([^}]+)}/g, (match, p1) => {
        switch (p1) {
          case 'HH': return date[`get${methods}Hours`]().toString().padStart(2, '0');
          case 'mm': return date[`get${methods}Minutes`]().toString().padStart(2, '0');
          case 'dd': return date[`get${methods}Date`]().toString();
          default: return p1;
        }
      });
    };

    // 生成数据（与官方示例几乎相同）
    const generateData = () => {
      const BREAK_GAP = '1%';
      const seriesData = [];
      const breaks = [];
      let time = new Date('2024-04-09T00:00:00Z');
      const endTime = new Date('2024-04-12T23:59:59Z').getTime();
      const todayCloseTime = new Date();
      
      // 更新交易日时间
      const updateDayTime = (time, todayCloseTime) => {
        roundTime(time, 'day', true);
        todayCloseTime.setTime(time.getTime());
        time.setUTCHours(9, 30); // 开盘时间
        todayCloseTime.setUTCHours(16, 0); // 收盘时间
      };
      
      updateDayTime(time, todayCloseTime);
      
      let valBreak = false;
      let val = 1669;
      
      for (; time.getTime() <= endTime; ) {
        let delta;
        if (valBreak) {
          delta = Math.floor((Math.random() - 0.5 * Math.sin(val / 1000)) * 20 * 100) / 10;
          valBreak = false;
        } else {
          delta = Math.floor((Math.random() - 0.5 * Math.sin(val / 1000)) * 20 * 100) / 100;
        }
        
        val = val + delta;
        val = +val.toFixed(2);
        
        seriesData.push([time.getTime(), val]);
        time.setMinutes(time.getMinutes() + 1);
        
        if (time.getTime() > todayCloseTime.getTime()) {
          // 使用 NaN 断开线条
          seriesData.push([time.getTime(), NaN]);
          
          const breakStart = todayCloseTime.getTime();
          time.setUTCDate(time.getUTCDate() + 1);
          updateDayTime(time, todayCloseTime);
          const breakEnd = time.getTime();
          
          valBreak = true;
          breaks.push({
            start: breakStart,
            end: breakEnd,
            gap: BREAK_GAP
          });
        }
      }
      
      return { seriesData, breaks };
    };

    // 初始化图表
    const initChart = () => {
      if (!chartRef.value) return;
      
      // 使用 l-echart 的初始化方法
      myChart = chartRef.value.init(echarts);
	  console.log('ssa',myChart)
      
      const DATA_ZOOM_MIN_VALUE_SPAN = 3600 * 1000;
      const _data = generateData();
      
      const option = {
        useUTC: true,
        title: {
          text: 'Intraday Chart with Breaks (Multiple Days)',
          left: 'center'
        },
        tooltip: {
          show: true,
          trigger: 'axis'
        },
        grid: {
          top: '20%',
          bottom: '30%'
        },
        xAxis: {
          type: 'time',
          axisLabel: {
            showMinLabel: true,
            showMaxLabel: true,
            formatter: function(timestamp) {
              const date = new Date(timestamp);
              const hours = date.getUTCHours().toString().padStart(2, '0');
              const minutes = date.getUTCMinutes().toString().padStart(2, '0');
              const day = date.getUTCDate();
              return `${hours}:${minutes}\n${day}d`;
            }
          },
          breaks: _data.breaks,
          breakArea: {
            expandOnClick: false,
            zigzagAmplitude: 0,
            zigzagZ: 200,
            itemStyle: {
              borderColor: 'none',
              opacity: 0
            }
          }
        },
        yAxis: {
          type: 'value',
          min: 'dataMin'
        },
        dataZoom: [
          {
            type: 'inside',
            minValueSpan: DATA_ZOOM_MIN_VALUE_SPAN
          },
          {
            type: 'slider',
            top: '73%',
            minValueSpan: DATA_ZOOM_MIN_VALUE_SPAN
          }
        ],
        series: [
          {
            type: 'line',
            symbolSize: 0,
            areaStyle: {},
            data: _data.seriesData
          }
        ]
      };

      myChart.setOption(option);
    };

    onMounted(() => {
      // 延迟初始化确保组件加载完成
      setTimeout(initChart, 300);
    });

    return {
      chartRef,
      initChart
    };
  }
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 600rpx;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>